package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.UserService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.PageUtil;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 	用户信息业务层实现类
 * 
 * @author xiet 2018年11月23日 下午2:41:59
 */
@Service
public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	private static final Integer REMARK_LENGTH = 50;
	private static final Integer USERCODE_LENGTH = 100;
	private static final String USERCODE = "admin";
	/**
	 * 注入mapper
	 */
	@Resource
	private UserMapper userMapper;
	@Resource
	private DepMapper deptsMapper;
	@Resource
	private MenuMapper menuMapper;
	@Resource
	private RoleRightMapper roleRightMapper;
	@Resource
	RoleMapper roleMapper;
	@Resource
	RoleUserMapper roleUserMapper;
	@Resource
	UploadMapper uploadMapper;

	/**
	 * 	删除用户信息（1启用，2删除，3停用）
	 */
	@Override
	public JSONObject deleteUser(Long[] lUserIdS, Integer lDataState) {
		try {
			//判断拆入id是否为1，超级用户不允许被删除
			for (Long lUserId : lUserIdS) {
				if(lUserId==1) {
					throw new ParamsErrorException("admin用户不允许被删除");
				}
			}
			// 判断传入的数据状态是否为空
			if (lDataState == null) {
				// 如果为空，抛出异常
				throw new ParamsErrorException("数据状态不能为空");
			} else if (lDataState != 1 && lDataState != 2 && lDataState != 3) {
				// 传入的数据状态不为1，2，3 抛出错误异常
				throw new ParamsErrorException("数据状态错误");
			}
			
			// 判断出入的用户id是否为空
			if (lUserIdS == null) {
				// 如果为空，抛出异常信息
				throw new ParamsErrorException("用户id不能为空");
			}
			int row = userMapper.deleteUser(lUserIdS, lDataState);
			String msg = "";
			if (row != 0) {
				// 判断传入的数据状态参数lDataState,返回相应信息
				switch (lDataState) {
				case 1:
					msg = "启用成功";
					break;
				case 2:
					msg = "删除成功";
					break;
				case 3:
					msg = "停用成功";
					break;
				default:
					break;
				}
			}
			return JSONObject.oK(msg);
		} catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 查询用户
	 */
	@Override
	public JSONObject queryUser(User user) {
		//声明listUser集合，用来装查询出来的参数
		List<User> listUser = null;
		try {
			Integer pagesize = user.getPagesize();
			Integer pageindex = user.getPageindex();
			if(pagesize != null && pageindex != null) {
				user.setIncept(pagesize*(pageindex - 1));
			}
			//获取用户id
			Integer lUserId = user.getUserId();
			//判断lUserId 是否存在，存在则是查询单个用户
			if(lUserId != null) {  
				listUser = userMapper.getUser(lUserId);
			} else{  
				//lUserId 不存在，则查询所有用户
				listUser = userMapper.listUser(user);
			}
			 //判断查询出来的集合是否为空
			if (listUser.isEmpty()) {
				return JSONObject.oK("没有用户相关数据", listUser, 0);
			}
			//用来记录查询出来的条数
			int count = userMapper.countUser(user);
            return JSONObject.oK("查询成功", listUser, count);
		} catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 查询用户
	 */
	/**
	 * wangqi
	 *
	 * 添加查询子部门下所有用户
	 * 19/9/9   9:10
	 *
	 * @param user
	 * @return
	 */
	@Override
	public JSONObject queryUserDep(User user) {
		//声明listUser集合，用来装查询出来的参数
		List<User> listUser = null;
		try {
			Integer pagesize = user.getPagesize();
			Integer pageindex = user.getPageindex();
			if(pagesize != null && pageindex != null) {
				user.setIncept(pagesize*(pageindex - 1));
			}

			// 判断 depId=null  显示第一条    0  全部
			Integer depId = user.getDepId();
			List<Integer> depIds = new ArrayList<>();
			if(depId==null){
				Dep dep = new Dep();
				dep.setDepPid(0);
				List<Dep> deps = deptsMapper.lookDepts(dep);
				if(deps != null && deps.size() >= 1){
					Dep dep1 = deps.get(0);
					depId=dep1.getDepId();
				}
			}else if(depId==0){
				user.setDepId(null);
			}

			if(depId!=null){
				// 递归加入子集
				depIds.add(depId);
				recursion(depIds,depId);
			}

			// 查询所有用户
      user.setDepIdArr(depIds);
			listUser = userMapper.queryUserByDepId(user);
			//判断查询出来的集合是否为空
			if (listUser.isEmpty()) {
				return JSONObject.oK("没有用户相关数据", listUser, 0);
			}
			//用来记录查询出来的条数
			int count = userMapper.countUserByDepId(user);
			return JSONObject.oK("查询成功", listUser, count);
		} catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * wangqi
	 *
	 * 递归查询子类 及其子类的子类
	 *
	 * 19/9/9   9:10
	 *
	 * @param depId
	 */
	private void recursion(List<Integer> depIds,Integer depId) {
		List<Integer> integers = deptsMapper.queryChild(depId);
		if(integers.size()>0){
			depIds.addAll(integers);
			for (Integer integer :integers){
				recursion(depIds,integer);
			}
		}
	}

	/**
	 * 	新增用户信息
	 */
	@Override
	public JSONObject insertUser(User user) {
		//判断基础信息是否符合数据库要求
		user.setDataState(1);
		if(user.getRemark()==null){
			user.setRemark("");
		}
		try {
			// 参数校验
			checkParam(user);
			//调用新增用户信息接口
			int row = userMapper.insertUser(user);
			   int lUserId = user.getUserId();
			if(row == 0) {
				throw new QueryFailedException("新增用户信息失败");
			}
			return JSONObject.build(200, "新增数据成功", lUserId);
		}catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject loginUser(User user) {
		if (StringUtils.isEmpty(user.getUserCode())) {
			return JSONObject.build(403, "用户名不能为空");
		}
		if (StringUtils.isEmpty(user.getUserPwd())) {
			return JSONObject.build(403, "密码不能为空");
		}
//		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserCode(), user.getUserPwd());
//		Subject subject = SecurityUtils.getSubject();
		User userLogin;
		List<Menu> menuList = null;
		String[] strings;
		Map<String ,Object > map=new HashMap<>();

		try {
//			subject.login(token);
//			userLogin = (User)SecurityUtils.getSubject().getPrincipal();
		 List<User>	userInfo =queryU(user);
			if (userInfo == null || userInfo.size() == 0) {
				throw new QueryFailedException("账号不存在");
			}
			if (!user.getUserPwd().equals(userInfo.get(0).getUserPwd())) {
				throw new QueryFailedException("密码错误!请检查输入");
			}
			userLogin=userInfo.get(0);
			//super_admin 超级管理员
			//admin	管理员
			//user	用户
			//tourists	游客
			User userXO=new User();
			userXO.setUserId(userLogin.getUserId());
			userXO.setUserName(userLogin.getUserName());
			userXO.setUserCode(userLogin.getUserCode());
			userXO.setRoleId(userLogin.getRoleId());
			userXO.setRoleName(userLogin.getRoleName());
			if (userXO.getUserId() == 1) {
				userXO.setAccess("super_admin");
//				menuList = menuMapper.selectMenuAll();
			} else {
				if(userXO.getRoleName()==null){
					userXO.setAccess("tourists");
				}else{
					if(userXO.getRoleName().contains("管理员")){
						userXO.setAccess("admin");
					}else{
						userXO.setAccess("user");
					}
				}
//				menuList = menuMapper.slectMenuByUserId(userLogin.getUserId());
			}
			map.put("user",userXO);
//			request.getSession().setAttribute("user", userLogin);
		} catch (GlobalException e) {
			return JSONObject.build(403, e.getMessage());
		}
		return JSONObject.oK("登陆成功",map,1);
	}

	@Override
	public JSONObject treeMenu(Integer lUserId) {
		try {

			List<XTreeNode> tree = null;

				tree = new ArrayList<>();
				List<XTreeNode> nodes = new ArrayList<>();
			List<Menu> list ;
				if(lUserId==1){
					list =menuMapper.selectMenuAll();
				}else {
					list =menuMapper.slectMenuByUserId(lUserId);
				}





				if (null != list) {
					for (Menu _MouldType : list) {
						XTreeNode node = new XTreeNode();
						node.setId(_MouldType.getMenuCode());
						node.setpId("00".equals(_MouldType.getMenuPcode()) ? null : _MouldType.getMenuPcode());
						node.setOpen(true);
						node.setTitle(_MouldType.getMenuName());
						nodes.add(node);
					}
				}
				tree = XCommonUtil.getTree(nodes, null);


			return JSONObject.oK("查询成功", tree, 1);
		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject arrayMenu(Integer lUserId) {
		try {
			List<Menu> menulist;
			if (lUserId == 1) {
				menulist =menuMapper.selectMenuAll();
			}else{
				menulist =menuMapper.slectMenuByUserId(lUserId);
			}
			String[] strings;
			strings=new String[menulist.size()] ;
			for (int i=0;i<menulist.size();i++) {
				strings[i]=menulist.get(i).getMenuCode();
			}
			return JSONObject.oK("查询成功", strings, menulist.size());


		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject listMenu(Integer lUserId) {
		try {
			List<Menu> menulist;
			if (lUserId == 1) {
				menulist =menuMapper.selectMenuAll();
			}else{
				menulist =menuMapper.slectMenuByUserId(lUserId);
			}

			return JSONObject.oK("查询成功", menulist, menulist.size());


		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject treeRole(Integer lRoleId) {

		try {
//			Role roleVO = roleMapper.selectRoles(lRoleId);
			return JSONObject.oK("查询成功");
		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject arrayRole(Integer lRoleId) {
		try {
			
			List<RoleRight> roleRightList = roleRightMapper.selectRoleRight(lRoleId);
			String[] strings;
			strings=new String[roleRightList.size()] ;
			for (int i=0;i<roleRightList.size();i++) {
				strings[i]=roleRightList.get(i).getVcMenuCode();
			}
			return JSONObject.oK("查询成功", strings, roleRightList.size());


		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject listRole(Integer lRoleId) {
		try {

			List<RoleRight> roleRightList = roleRightMapper.selectRoleRight(lRoleId);

			return JSONObject.oK("查询成功", roleRightList, roleRightList.size());


		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 修改用户信息
	 *
	 * wangqi
	 *
	 * 新增用户编码不允许更改判断
	 *
	 * 19/9/4  16:34
	 */
	@Override
	public JSONObject updateUser(User user) {
		try { 
			//判断用户编码是否为admin,admin用户不允许被修改
			if((USERCODE).equals(user.getUserCode())) {
				throw new ParamsErrorException("超级用户admin不允许被修改信息");
			}
			//判断用户编码是否更改
			int num = userMapper.judgeUserCode(user);
			if(num == 0) {
				throw new ParamsErrorException("用户编码不允许更改");
			}
			// 参数校验
			checkParam(user);
			//调用修改的接口
			int row = userMapper.updateByPrimaryKeySelective(user);
			if(row == 0) {
				throw new QueryFailedException("更新用户信息失败");
			}
			return JSONObject.oK("更新成功");
		} catch(GlobalException e){//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}
	
	/**
	 * 根据用户名查询用户
	 */
	@Override
	public List<User> queryU(User user){
		//声明listU集合，用来装通过用户名查询出来的用户
		List<User> listU = null;
		//调用接口通过用户名查询用户
		listU = userMapper.lU(user);
		//判断集合是否为空
		if(listU.isEmpty()) {
			throw new QueryFailedException("没有相关数据");
		}
		return listU;
	}

	/**
	 * 通过角色ID查询该角色未设置的用户
	 *
	 * @param
	 * @return java.util.List<com.indusfo.spc.pojo.User>
	 * @author xuz
	 * @date 2019/7/17 3:46 PM
	 */
	@Override
	public List<User> queryUserByRoleId(Role role) {
//		if (null == role.getRoleId()) {
//			throw new ParamsErrorException("角色ID不能为空");
//		}
		// 分页计算
        PageUtil.calculatePageSize(role);
		List<User> userList = userMapper.queryUserByRoleId(role);
		return userList;
	}

	/**
	 * 通过角色ID查询该角色未设置的用户数量
	 *
	 * @param role
	 * @return java.lang.Integer
	 * @author xuz
	 * @date 2019/7/17 4:52 PM
	 */
    @Override
    public Integer getCountsByRoleId(Role role) {
        Integer count = userMapper.queryCountsByRoleId(role);
        return count;
    }


	/**
	 * 参数校验
	 *
	 * @param user
	 *
	 */
	private void checkParam(User user) {
		//查询所有用户的用户编码
		String vcRemark = user.getRemark();
		if(vcRemark==null){
			vcRemark="";
		}
		//判断传入的参数是否符合规定长度
		if((USERCODE).equals(user.getUserCode())) {
			throw new ParamsErrorException("admin为超级用户，只允许存在一个");
		}
		if(("").equals(user.getUserCode())) {
			throw new ParamsErrorException("用户编码不能为空");
		}
        if(("").equals(user.getUserPwd())) {
            throw new ParamsErrorException("用户密码不能为空");
        }
		if(user.getUserCode().getBytes().length>REMARK_LENGTH) {
			throw new ParamsErrorException("用户编码长度过长");
		}
		if(vcRemark.getBytes().length>USERCODE_LENGTH) {
			throw new ParamsErrorException("说明长度过长");
		}
        //判断用户编码是否存在
        int num = userMapper.listUserCode(user);
        if(num != 0) {
            throw new ParamsErrorException("用户编码已存在");
        }
		if(user.getDataState()==null){
			user.setDataState(1);
		}
	}

	@Override
	public String checkNoRepeat(User user) {
		//查询所有用户的用户编码
		String vcRemark = user.getRemark();
		if(vcRemark==null){
			vcRemark="";
		}
		String depName=user.getDepName();
		//首先先判断一下当前行是否为空
		if(StringUtils.isBlank(user.getUserCode()) && StringUtils.isBlank(user.getUserPwd()) && StringUtils.isBlank(depName)){
			return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
		}

		//判断传入的参数是否符合规定长度
		if((USERCODE).equals(user.getUserCode())) {
			return "admin为超级用户，只允许存在一个";
		}

		if(StringUtils.isBlank(user.getUserCode())) {
			return "用户编码不能为空";
		}
		if(StringUtils.isBlank(user.getUserPwd())) {
			return "用户密码不能为空";
		}
		if(user.getUserCode().getBytes().length>REMARK_LENGTH) {
			return "用户编码长度过长";
		}
		if(vcRemark.getBytes().length>USERCODE_LENGTH) {
			return "说明长度过长";
		}
		if(StringUtils.isBlank(depName)){
			return "部门名称不能为空";
		}
		//判断用户编码是否存在
		int num = userMapper.listUserCode(user);
		if(num != 0) {
			return "用户编码已存在";
		}
		Map<String, Dep> depMap = uploadMapper.queryDep();
		if(depMap.containsKey(depName)){
			Dep get =depMap.get(depName);
			user.setDepId(get.getDepId());
		}else{
			return "部门名称填写错误/不规范";
		}
		if(user.getDataState()==null){
			user.setDataState(1);
		}

		return null;
	}

	@Override
	public JSONObject updateListUser(List<User> userList) {
        int flag = uploadMapper.updateListUser(userList);
        if(flag>0){
            JSONObject.oK("新增成功");
        }
        return JSONObject.oK("新增失败");
	}
}
